package controller;

import com.root.health.bean.CorrelationInfo;
import com.root.health.bean.ElderhealthInfo;
import com.root.health.bean.UserInfo;
import com.root.health.service.CorrelationService;
import com.root.health.service.HealthInfoService;
import com.root.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class HealthInfoController {
    @Autowired
    HealthInfoService healthInfoService;
    @Autowired
    UserService userService;
    @Autowired
    CorrelationService correlationService;
    @Autowired
    CorrelationController correlationController;
    /**
     *
     * 添加基本健康信息
     */
    @GetMapping("healthinfo")
   
    public String healthinfoPage(UserInfo userInfo, ElderhealthInfo elderhealthInfo, HttpSession session, Model model, HttpServletRequest request){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        elderhealthInfo.setElderUserId(userInfo.getUserId());
        //测试System.out.println(elderhealthInfo.getElderUserId());
        //将当前用户id添加到用户基本健康信息中
        Date date = new Date(System.currentTimeMillis());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datestr = dateFormat.format(date);
        Timestamp time = Timestamp.valueOf(datestr);
        //将当前系统时间添加到用户基本健康信息中
        if(userInfo.getRole().equals("children")){
            //如果当前用户角色为子女，则在添加之前先跳转到选择已关联的父母角色页面，再跳转到子女角色添加方法
            session.setAttribute("elderhealthInfo",elderhealthInfo);
            List<Map<String,Object>> userMapList;
            userMapList = correlationController.ChildrenCorrUser(userInfo);
            model.addAttribute("userMapList",userMapList);
            return "selectuserHealth";
        }else if(userInfo.getRole().equals("parents")){
            if(healthInfoService.healthByDate(elderhealthInfo.getHealthDate()) == null){
                try {
                    healthInfoService.elderHealthInfo(elderhealthInfo.getHeight(), elderhealthInfo.getWeight(), elderhealthInfo.getSystolicPressure(),
                            elderhealthInfo.getDiastolicPressure(), elderhealthInfo.getTemperature(),elderhealthInfo.getGlucose(),
                            elderhealthInfo.getHeartbeat(), elderhealthInfo.getElderUserId(),time);
                    session.setAttribute("elderHealth", elderhealthInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                    model.addAttribute("errormsg","健康信息添加出错");
                    return "error";//如果新添加信息的日期已存在，则判断为该条数据已在数据库中，不执行添加操作
                }
                model.addAttribute("successHref","selecthealthinfo");
                return "success";//做重复性校验防止信息重复添加
            }else{
                model.addAttribute("errormsg","健康信息添加重复");
                return "error";//如果新添加信息的日期已存在，则判断为该条数据已在数据库中，不执行添加操作
            }
        }else{
            model.addAttribute("errormsg","添加健康信息功能用户角色错误");
            return "error";
        }
    }
    /**
     *
     * 子女用户添加健康信息
     */

    @PostMapping("childrenHealhAdd")
    public String childrenHealhAdd(ElderhealthInfo elderhealthInfo,HttpSession session, Model model, HttpServletRequest request){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        String username = request.getParameter("healthUsername");
        session.setAttribute("username",username);
        Date date = new Date(System.currentTimeMillis());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datestr = dateFormat.format(date);
        Timestamp time = Timestamp.valueOf(datestr);
        elderhealthInfo = (ElderhealthInfo) session.getAttribute("elderhealthInfo");
        elderhealthInfo.setElderUserId(userService.getUserbyName(username).getUserId());
        if(healthInfoService.healthByDate(elderhealthInfo.getHealthDate()) == null){
            healthInfoService.elderHealthInfo(elderhealthInfo.getHeight(), elderhealthInfo.getWeight(), elderhealthInfo.getSystolicPressure(),
                    elderhealthInfo.getDiastolicPressure(), elderhealthInfo.getTemperature(), elderhealthInfo.getGlucose(),
                    elderhealthInfo.getHeartbeat(), elderhealthInfo.getElderUserId(), time);
            session.setAttribute("elderHealth", elderhealthInfo);
            model.addAttribute("successHref","selecthealthinfo");
            return "success";//做重复性校验防止信息重复添加
        }else{
            model.addAttribute("errormsg","子女用户添加健康信息重复");
            return "error";//如果新添加信息的日期已存在，则判断为该条数据已在数据库中，不执行添加操作
        }
    }
    /**
     *
     * 健康信息查询
     */
    @GetMapping("selecthealthinfo")
    public String selecthealthinfo(ElderhealthInfo healthInfo,UserInfo userInfo,Model model,HttpSession session){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }
        UserInfo tempo_user = (UserInfo) session.getAttribute("loginUser");
        userInfo = userService.getUserbyName(tempo_user.getUserName());
        //由于Session传递来的用户是前端页面中输入的用户实体类，没有被数据库增加userid，所以需要再从数据库查询一次当前用户获取userid
        List<ElderhealthInfo> healthList;
        List<Map<String,Object>> healthMapList = new LinkedList<>();
        if(userInfo.getRole().equals("parents")){
            healthList = healthInfoService.healthByid(userInfo.getUserId());
            for (int i = 0; i < healthList.toArray().length; i++) {
                ElderhealthInfo health = healthList.get(i);
                healthMapList.add(sethealthMapList(health));
            }
            model.addAttribute("healthMapList",healthMapList);
            return "selecthealth";//如果当前用户角色为父母，仅查询该用户的健康信息
        }else if(userInfo.getRole().equals("children")){
            //如果当前用户角色为子女，则先从关联信息表查询该角色关联用户id，再以list形式查询对应id的体检信息
            List<CorrelationInfo> list_corr = correlationService.parentidgetByid(userInfo.getUserId());
            for (int i = 0; i < list_corr.toArray().length; i++) {
                if(list_corr.get(i)==null){
                    break;//若本次循环中list_corr不存在，则跳出整个循环防止出现数组越界错误
                }
                List<ElderhealthInfo> userHealthList = healthInfoService.healthByid(list_corr.get(i).getParentid());
                for (int j = 0; j < userHealthList.toArray().length; j++) {
                    ElderhealthInfo userHealth = userHealthList.get(j);
                    if(userHealth==null){
                        break;//若本次循环中userHealth不存在，则跳出整个循环防止出现数组越界错误
                    }
                    healthMapList.add(sethealthMapList(userHealth));
                    //将已检索信息放入Map中传入前端（因为userName不在ElderhealthInfo中，所以需要用Map整合信息
                }
            }
            model.addAttribute("healthMapList",healthMapList);
            //model.addAttribute("nameList",nameList);
            return "selecthealth";
        }else{
            model.addAttribute("errormsg","健康信息查询功能用户角色错误");
            return "error";
        }
    }
    /**
     *
     * 从健康信息查询页面携带参数实现删除操作
     */

    @PostMapping("healthDel")
    public String healthDel(){

        return "selecthealth";
    }

    @GetMapping("healthDel")
    public String healthDel(long healthid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        //测试用System.out.println(medName);
        //healthid参数从selecthealth页面使用@{/medicationLinkDel(medName=${medicine.medicineName})}传递而来
        session.setAttribute("healthid",healthid);
        healthInfoService.healthDel(healthid);
        model.addAttribute("successHref","selecthealthinfo");
        return "success";
    }//从药品查询页面携带药品名参数实现删除操作

    /**
     *
     * 修改操作的中间方法
     */
    @GetMapping("healthUpdLink")
    public String healthUpdLink(long healthid,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        session.setAttribute("healthid",healthid);
        return "healthUpd";
    }
    /**
     *
     * 从健康信息查询页面携带参数实现修改操作
     */

    @GetMapping("healthUpd")
    public String healthUpd(){

        return "healthUpd";
    }
    @PostMapping("healthUpd")
    public String healthUpd(ElderhealthInfo healthinfo,HttpSession session,Model model){
        if(session.getAttribute("loginUser") == null){
            //如果当前用户信息为空，传递message请重新登录
            model.addAttribute("msg","请重新登录");
            //回到登录页面
            return "login";
        }//登录拦截器
        long healthid = (long) session.getAttribute("healthid");
        healthInfoService.healthUpd(healthid,healthinfo.getHeight(),healthinfo.getWeight(),healthinfo.getSystolicPressure(),
                healthinfo.getDiastolicPressure(),healthinfo.getTemperature(),healthinfo.getGlucose(),healthinfo.getHeartbeat());
        model.addAttribute("successHref","selecthealthinfo");
        return "success";
    }
    //设置健康信息MapList
    public Map<String,Object> sethealthMapList(ElderhealthInfo health){
        String stryear = String.valueOf(health.getHealthDate()).substring(0,10);
        String strdate = String.valueOf(health.getHealthDate()).substring(11,16);
        double height = health.getHeight()/100.0;
        double weight = health.getWeight();
        String BMIStr = "正常";
        String BMIClass = "label label-Green3";
        double BMILong = weight/(height*height);
        int BMIWarning = 0;
        if(BMILong<=18.4){
            BMIStr = "偏瘦";
            BMIClass = "label label-SlateGrey";
            BMIWarning = 1;
        }else if(BMILong>=24.0&&BMILong<=27.9){
            BMIStr = "过重";
            BMIClass = "label label-Gold1";
            BMIWarning = 1;
        }else if(BMILong>=28.0){
            BMIStr = "肥胖";
            BMIClass = "label label-danger";
            BMIWarning = 1;
        }//BMI计算
        double systolicPressure = health.getSystolicPressure();
        double diastolicPressure = health.getDiastolicPressure();
        String pressure = "正常血压";
        String pressureClass = "label label-info";
        int pressureWarning = 0;
        if(systolicPressure>=140||diastolicPressure>=90){
            pressure = "高血压";
            pressureClass = "label label-danger";
            pressureWarning = 1;
        }else if(systolicPressure<=90||diastolicPressure<=60){
            pressure = "低血压";
            pressureClass = "label label-MediumSlateBlue";
            pressureWarning = 1;
        }//血压判断
        double glucose = health.getGlucose();
        String glucoseStr = "正常";
        String glucoseClass = "label label-info";
        int glucoseWarning = 0;
        if(glucose<=3.6){
            glucoseStr = "低血糖";
            glucoseClass = "label label-MediumSlateBlue";
            glucoseWarning = 1;
        }else if(glucose>=6.1){
            glucoseStr = "高血糖";
            glucoseClass = "label label-danger";
            glucoseWarning = 1;
        }//血糖判断
        long heartBeat = health.getHeartbeat();
        String heartBeatClass = "label label-Khaki1";
        String heartBeatStr = "心率正常";
        int heartBeatWarning = 0;
        if(heartBeat<60){
            heartBeatStr = "心率过缓！";
            heartBeatClass = "label label-danger";
            heartBeatWarning = 1;
        }else if(heartBeat>100){
            heartBeatStr = "心率过速！";
            heartBeatClass = "label label-danger";
            heartBeatWarning = 1;
        }//心率判断
        double temperature = health.getTemperature();
        String temperatureClass = "label label-Khaki1";
        String temperatureStr = "体温正常";
        int temperatureWarning = 0;
        if(temperature>=37.3&&temperature<=38.0){
            temperatureClass = "label label-danger";
            temperatureStr = "低烧！";
            temperatureWarning = 1;
        }else if(temperature>=38.1&&temperature<=40){
            temperatureClass = "label label-danger";
            temperatureStr = "高烧！";
            temperatureWarning = 1;
        }else if(temperature>=40.1){
            temperatureClass = "label label-danger";
            temperatureStr = "体温过高！有生命危险！";
            temperatureWarning = 1;
        }
        String finalBMIStr = BMIStr;
        String finalBMIClass = BMIClass;
        String finalPressure = pressure;
        String finalPressureClass = pressureClass;
        String finalGlucoseStr = glucoseStr;
        String finalGlucoseClass = glucoseClass;
        int finalBMIWarning = BMIWarning;
        int finalPressureWarning = pressureWarning;
        int finalGlucoseWarning = glucoseWarning;
        String finalHeartBeatClass = heartBeatClass;
        String finalHeartBeatStr = heartBeatStr;
        String finalTemperatureClass = temperatureClass;
        String finalTemperatureStr = temperatureStr;
        int finalHeartBeatWarning = heartBeatWarning;
        int finalTemperatureWarning = temperatureWarning;
        return new HashMap<>(){{
            put("id",health.getHealthId());
            put("year", stryear);
            put("date", strdate);
            put("height",health.getHeight());
            put("weight",health.getWeight());
            put("BMI", finalBMIStr);
            put("BMIClass", finalBMIClass);
            put("BMIWarning", finalBMIWarning);
            put("pressure", finalPressure);
            put("pressureClass", finalPressureClass);
            put("systolicPressure",health.getSystolicPressure());
            put("diastolicPressure",health.getDiastolicPressure());
            put("pressureWarning", finalPressureWarning);
            put("temperature",health.getTemperature());
            put("temperatureClass", finalTemperatureClass);
            put("temperatureStr", finalTemperatureStr);
            put("temperatureWarning", finalTemperatureWarning);
            put("glucose",glucose);
            put("glucoseStr", finalGlucoseStr);
            put("glucoseClass", finalGlucoseClass);
            put("glucoseWarning", finalGlucoseWarning);
            put("heartbeat",health.getHeartbeat());
            put("heartBeatClass", finalHeartBeatClass);
            put("heartBeatStr", finalHeartBeatStr);
            put("heartBeatWarning", finalHeartBeatWarning);
            put("realName",userService.getUserbyId(health.getElderUserId()).getRealname());
        }};
    }
}
